package com.puer.controller;

import com.puer.common.Code;
import com.puer.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/img")
public class ImgController {
    // 图片保存路径
    @Value("${file-save-path}")
    private String fileSavePath;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取项目根目录
//        String projectRootPath = System.getProperty("user.dir");
        // 文件保存目录  D:/实训/普洱学院/实训/2025-10-24/images
        Path dirPath = Paths.get(fileSavePath);
        try {
            // 给文件重新设置一个名字
            // 后缀
            String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

            // 创建这个新文件
            Path newFilePath = dirPath.resolve(newFileName);

            // 复制操作
            file.transferTo(newFilePath.toFile());

            // 协议 :// ip地址 ：端口号 / 文件目录(/images/2024/05/24/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + newFileName;
            System.out.println("图片上传，访问URL：" + url);
            return Result.builder().data(url).message("上传成功！").code(Code.SAVE_OK).build();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.builder().data(null).message("IO异常！").code(Code.SAVE_ERR).build();
        }
    }
}
